<?php

namespace App\Console\Commands;

use App\Jobs\WarningMessage;

use App\User;
use Illuminate\Console\Command;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class UserWarningCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user:warning';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '设备电量低告警';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $date = date('Y-m-d');

        try {
            $users = User::with(['tevice' => function($query) {
                $query->select(['id', 'mobile', 'du', 'house_id']); // 增加house_id字段
            }])
                ->where('type', 'tenant')
                ->where('sub_2', 1)
                ->where(function($q) use ($date) {
                    $q->where('warning_date', '!=', $date)
                        ->orWhereNull('warning_date');
                })
                ->whereHas('tevice', function($query) {
                    $query->whereColumn('user.sub_warning', '>', 'device.du') // 替换whereRaw
                    ->whereNotNull('mobile');
                })
                ->limit(30)
                ->get();

            foreach ($users as $user) {
                if ($user->tevice) {  // 保持原有的判断
                    dispatch(new WarningMessage([
                        'user_id' => $user->id,
                        'openid' => $user->openid,
                        'house_id' => $user->tevice->house_id ?? 0, // 改用tevice获取
                        'du' => $user->tevice->du ?? 0
                    ]));
                }
                $user->warning_date = $date;
                $user->save();
            }

            return 0;
        } catch (\Exception $e) {
            Log::error('告警任务执行失败: '.$e->getMessage());
            return 1;
        }
    }


}
